package com.lwq.lwqmicoservice.common.service;

import com.auth0.jwt.interfaces.Claim;
import com.lwq.lwqmicoservice.common.exception.AuthenticationException;
import com.lwq.lwqmicoservice.common.util.TokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * Description:
 * Author: LiuWenQing
 * Datetime: 2021/6/11
 */
@Component
public class TokenService {

    @Autowired(required=false)
    private HttpServletRequest request;
    @Value("${token.header}")
    private String tokenHeader;


    /**
     * 获取用户身份信息
     * @return userId
     */
    public Long getUserId(){
        String token = getToken(request);
        if (StringUtils.isNotEmpty(token) && !token.equals("undefined") && !token.equals("null")) {
            Map<String, Claim> map;
            try{
                map = TokenUtil.verifyToken(token);
            }catch(Exception e){
                return null;
//                throw new AuthenticationException("令牌解析错误");
            }
            return map.get("userId").asLong();
        }
        return null;
    }

    /**
     * 获取用户身份信息
     * @return userName
     */
    public String getUserName(){
        String token = getToken(request);
        if (StringUtils.isNotEmpty(token) && !token.equals("undefined") && !token.equals("null")) {
            Map<String, Claim> map;
            try{
                map = TokenUtil.verifyToken(token);
            }catch(Exception e){
                throw new AuthenticationException("令牌解析错误");
            }
            return map.get("userName").asString();
        }
        return "";
    }

    /**
     * 获取用户身份信息
     * @return userName
     */
    public String getName(){
        String token = getToken(request);
        if (StringUtils.isNotEmpty(token) && !token.equals("undefined") && !token.equals("null")) {
            Map<String, Claim> map;
            try{
                map = TokenUtil.verifyToken(token);
            }catch(Exception e){
                return null;
//                throw new AuthenticationException("令牌解析错误");
            }
            return map.get("name").asString();
        }
        return "";
    }

    /**
     * 获取请求token
     *
     * @param request
     * @return token
     */
    private String getToken(HttpServletRequest request)
    {
        String token = request.getHeader(tokenHeader);
        return StringUtils.isEmpty(token) ? null :TokenUtil.cutTokenBearer(token);
    }
}
